package org.jim.server.demo.command;

import org.jim.core.ImChannelContext;
import org.jim.core.ImConst;
import org.jim.core.ImPacket;
import org.jim.core.exception.ImException;
import org.jim.core.http.HttpRequest;
import org.jim.core.packets.Command;
import org.jim.core.packets.LoginReqBody;
import org.jim.core.utils.JsonKit;
import org.jim.core.ws.WsRequestPacket;
import org.jim.server.JimServerAPI;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.LoginReqHandler;
import org.jim.server.processor.handshake.WsHandshakeProcessor;

public class WebWsHandshakeProcessor extends WsHandshakeProcessor {

    /**
     * 对httpResponsePacket参数进行补充并返回，如果返回null表示不想和对方建立连接，框架会断开连接，如果返回非null，框架会把这个对象发送给对方
     * @param packet
     * @param imChannelContext
     * @return
     * @throws Exception
     * @author: WChao
     */
    @Override
    public final ImPacket handshake(ImPacket packet, ImChannelContext imChannelContext) throws ImException {
        WsRequestPacket request = (WsRequestPacket)packet;
        if(!this.loginHake(request)){
            return null;
        }
        return super.handshake(packet,imChannelContext);
    }


    @Override
    public final void onAfterHandshake(ImPacket packet, ImChannelContext imChannelContext) throws ImException {
        LoginReqHandler loginHandler = (LoginReqHandler) CommandManager.getCommand(Command.COMMAND_LOGIN_REQ);
        HttpRequest request = (HttpRequest)packet;
        LoginReqBody loginReqBody = this.getLoginReqBody(request);
        byte[] loginBytes = JsonKit.toJsonBytes(loginReqBody);
        request.setBody(loginBytes);
        try{
            request.setBodyString(new String(loginBytes, ImConst.CHARSET));
        }catch (Exception e){
            throw new ImException(e);
        }
        ImPacket loginRespPacket = loginHandler.handler(request, imChannelContext);
        if(loginRespPacket != null){
            JimServerAPI.send(imChannelContext, loginRespPacket);
        }
    }
    //验证是否可以登录
    public boolean loginHake(WsRequestPacket request) {
        return true;
    }
    //返回登录人账号，密码，token
    public LoginReqBody getLoginReqBody(HttpRequest request) {
        String username = request.getParams().get("username") == null ? null : (String)request.getParams().get("username")[0];
        String password = request.getParams().get("password") == null ? null : (String)request.getParams().get("password")[0];
        String token = request.getParams().get("token") == null ? null : (String)request.getParams().get("token")[0];
        return new LoginReqBody(username,password,token);
    }
}
